package com.douyuehan.doubao.wechatpay.utils;


import java.util.Map;
import java.util.Set;

public class WeChatApi {

    private final static String MINI_JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=${APPID}&secret=${SECRET}&js_code=${CODE}";
    private final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}";
    private final static String GET_JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${ACCESS_TOKEN}&type=jsapi";


    public static String jscode2sessionUrl(String code) {
        return MINI_JSCODE2SESSION_URL.replace("${APPID}", "1")
                .replace("${SECRET}", "2")
                .replace("${CODE}", code);
    }


    public static String tokenUrl() {
        return getUrl(TOKEN_URL);
    }


    public static String getJsapiTicketUrl(String token) {
        return GET_JSAPI_TICKET_URL.replace("${ACCESS_TOKEN}", token);
    }


    public static String getUrl(String url) {
        return url.replace("${APPID}", Constants.APPID).replace("${SECRET}", Constants.APP_SECRECT);
    }

    public static String getUrl(String url, Map<String, String> map) {
        String resultUrl = getUrl(url);
        if (map == null) return resultUrl;
        Set<String> keys = map.keySet();
        for (String key : keys) {
            resultUrl = resultUrl.replace(String.format("${%s}", key.toUpperCase()), map.get(key));
        }
        return resultUrl;
    }

}
